package redisinit

import (
	"cartsrv/cartsrv"
	"context"
	"fmt"
	"strconv"
)

func CartAdd(userId, goodsId, goodsNumber int, goodsTitle, goodsStyle, goodsCover string, price float64) error {
	key := fmt.Sprintf("cart:user_id_:%d:goods_id_%d", userId, goodsId)
	return RDb.HMSet(context.Background(), key, map[string]interface{}{
		"userId":      userId,
		"goodsNumber": goodsNumber,
		"goodsTitle":  goodsTitle,
		"goodsCover":  goodsCover,
		"price":       price,
		"goodsStyle":  goodsStyle,
		"checked":     1,
	}).Err()
}

func CartList(userId int) (cartList []*cartsrv.CartList, err error) {
	key := fmt.Sprintf("cart:user_id_:%d:goods_id_%d", userId)
	keys := RDb.Keys(context.Background(), key).Val()
	for _, v := range keys {
		goodsInfo := RDb.HGetAll(context.Background(), v).Val()
		goodsId, _ := strconv.Atoi(goodsInfo["goodsId"])
		goodsNumber, _ := strconv.Atoi(goodsInfo["goodsNumber"])
		checked, _ := strconv.Atoi(goodsInfo["checked"])
		goodsTitle, _ := goodsInfo["goodsTitle"]
		goodsCover, _ := goodsInfo["goodsCover"]
		goodsStyle, _ := goodsInfo["goodsStyle"]
		price, _ := strconv.ParseFloat(goodsInfo["price"], 64)
		cartList = append(cartList, &cartsrv.CartList{
			UserId:      int64(userId),
			GoodsId:     int64(goodsId),
			GoodsTitle:  goodsTitle,
			Price:       float32(price),
			GoodsNumber: int64(goodsNumber),
			Checked:     int64(checked),
			GoodsCover:  goodsCover,
			GoodsStyle:  goodsStyle,
		})
	}
	return
}

func CleanCart(userId int) (err error) {
	//清除购物车全部商品数据
	key := fmt.Sprintf("cart:user_id_:%d:*", userId)
	keys := RDb.Keys(context.Background(), key).Val()
	for _, v := range keys {
		RDb.Del(context.Background(), v)
	}
	return
}
func CartTotal(userId int) (TotalAmount float64, TotalCount int) {
	//统计数量和总金额
	key := fmt.Sprintf("cart:user_id_:%d:*", userId)
	keys := RDb.Keys(context.Background(), key).Val()
	for _, v := range keys {
		goodsInfo := RDb.HGetAll(context.Background(), v).Val()
		price, _ := strconv.ParseFloat(goodsInfo["price"], 64)
		number, _ := strconv.Atoi(goodsInfo["goodsNumber"])
		TotalCount += number
		TotalAmount += price * float64(number)
	}
	return
}
